@file:Suppress("unused")

package com.example.demo.model.blog

import xyz.erupt.annotation.*
import xyz.erupt.annotation.`fun`.*
import xyz.erupt.annotation.sub_erupt.*
import xyz.erupt.annotation.sub_field.*
import xyz.erupt.annotation.sub_field.sub_edit.*
import xyz.erupt.core.config.*
import xyz.erupt.core.prop.EruptProp
import xyz.erupt.upms.model.base.*
import java.awt.image.*
import java.io.*
import javax.annotation.*
import javax.imageio.*
import javax.persistence.*
import kotlin.jvm.Transient

@Erupt(
    name = "图片管理",
    dataProxy = [Pictures::class],
    power = Power(edit = false),
    linkTree = LinkTree(dependNode = true, field = "picturesCategory"),
)
@Table(name = "blog_picture")
@Entity // 由于需要实现 DataProxy 接口，因此这里不适合使用数据类，而是采用普通类
class Pictures : HyperModel(), DataProxy<Pictures> {
    @EruptField(
        views = [View(title = "缩略图", type = ViewType.IMAGE)],
        edit = Edit(title = "图片地址", notNull = true, type = EditType.ATTACHMENT),
    )
    var filePath: String = ""

    @EruptField(
        views = [
            View(
                title = "大小",
                template = "(value/1024/1024).toFixed(2) + 'MB'",
            ),
        ],
    )
    var sizes: Long? = null

    @EruptField(
        views = [View(title = "宽度")],
        edit = Edit(title = "宽度", show = false, search = Search(vague = true)),
    )
    var width: Int? = null

    @EruptField(
        views = [View(title = "高度")],
        edit = Edit(title = "高度", show = false, search = Search(vague = true)),
    )
    var height: Int? = null

    @EruptField(
        views = [View(title = "备注")],
        edit = Edit(title = "图片备注", type = EditType.TEXTAREA),
    )
    var remark: String? = null

    @ManyToOne
    var picturesCategory: PicturesCategory? = null

    @Transient
    @Resource
    lateinit var eruptProp: EruptProp

    override fun beforeAdd(pictures: Pictures) {
        val file = File(eruptProp.uploadPath + pictures.filePath)
        try {
            val bufferedImage: BufferedImage = ImageIO.read(FileInputStream(file))
            pictures.height = bufferedImage.height
            pictures.width = bufferedImage.width
            pictures.sizes = file.length()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
}